import os
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.exceptions import RequestValidationError
from app.config import settings
from app.core.events import startup, shutdown
from app.core.logging import setup_logging
from app.core.logging_middleware import logging_middleware
from app.modules.users.router import router as users_router, public_router as users_public_router
from app.modules.permissions.router import router as permissions_router
from app.modules.roles.router import router as roles_router
from app.modules.logs.router import router as logs_router
from app.modules.system.router import router as system_router, public_router as system_public_router
from app.modules.files.router import router as files_router
from app.core.exceptions import exception_handler

# 初始化日志系统
setup_logging()

# --- 创建上传目录 ---
upload_path = Path("uploads")
upload_path.mkdir(exist_ok=True)

app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    description=settings.DESCRIPTION,
)

# 使用装饰器注册高性能日志中间件
# 这种方式是FastAPI的推荐实践
app.middleware("http")(logging_middleware)


# 注册事件处理器
app.add_event_handler("startup", startup(app))
app.add_event_handler("shutdown", shutdown(app))


# 注册全局异常处理器
app.add_exception_handler(Exception, exception_handler)
app.add_exception_handler(RequestValidationError, exception_handler)


# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
    allow_methods=settings.CORS_ALLOW_METHODS,
    allow_headers=settings.CORS_ALLOW_HEADERS,
)

# --- 挂载静态文件目录 ---
# 用户可以通过 /static/uploads/... 来访问上传的文件
app.mount("/static/uploads", StaticFiles(directory=upload_path), name="static_uploads")


# 注册路由
app.include_router(users_public_router)
app.include_router(users_router)
app.include_router(permissions_router)
app.include_router(roles_router)
app.include_router(logs_router)
app.include_router(system_public_router)  # 公开接口
app.include_router(system_router)  # 需要认证的接口
app.include_router(files_router)


# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="0.0.0.0", port=8100, reload=True, debug=True)


"""
项目运行步骤
迁移文件配置：uv run python -m aerich init -t app.db.config.TORTOISE_ORM
迁移数据库：uv run python -m aerich init-db
后续数据库模型变动:
    更新迁移文件：uv run python -m aerich migrate
    执行迁移：uv run python -m aerich upgrade

# uv启动项目
uv run uvicorn app.main:app --host 0.0.0.0 --port 8100 --reload
uv run python -m uvicorn app.main:app --host 0.0.0.0 --port 8100 --reload
"""